package com.zoro.k8sapp.app.producer.controller;

import com.zoro.k8sapp.commondto.common.BriefInfo;
import com.zoro.k8sapp.commonutil.network.NetworkUtil;
import com.zoro.k8sapp.feignapi.basicinfo.ApplicationInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.SocketException;
import java.util.Objects;

/**
 * @author zhaoxingwu
 */
@RestController
@RequestMapping("/info")
public class ProducerInfoController implements ApplicationInfo {


    private static final String APPLICATION_PORT = "server.port";
    private static final String CONTAINER_PORT = "k8s.info.containerPort";
    private static final String POD_NAME = "k8s.info.podName";
    private static final String CLUSTER_IP = "k8s.info.clusterIp";
    private final Environment environment;

    public ProducerInfoController(Environment environment) {
        this.environment = environment;
    }

    @Override
    public BriefInfo briefInfo() throws SocketException {
        BriefInfo info = new BriefInfo();

        String localPort = environment.getProperty(APPLICATION_PORT);
        if (StringUtils.isBlank(localPort)) {
            info.setLocalPort(-1);
        } else {
            info.setLocalPort(Integer.parseInt(localPort));
        }

        info.setHostIp(NetworkUtil.getIp());
        int containerPort;
        try {
            containerPort = Integer.parseInt(Objects.requireNonNull(environment.getProperty(CONTAINER_PORT)));
        } catch (Exception e) {
            containerPort = -1;
        }
        info.setContainerPort(containerPort);
        info.setClusterIp(environment.getProperty(CLUSTER_IP));
        info.setPodName(environment.getProperty(POD_NAME));
        return info;
    }
}
